package com.yaowk.authc.realm;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.yaowk.authc.model.Permission;
import com.yaowk.authc.model.Role;
import com.yaowk.authc.model.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;

import java.util.List;

/**
 * Created by yaowenkai on 2017/3/28.
 */

/**
 * shiro获取用户信息和权限
 */
public class JdbcRealm extends AuthorizingRealm {
    @Override
    public String getName() {
        return "JdbcRealm";
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        Integer id = user.getInt("id");
        // 先查找缓存
        SimpleAuthorizationInfo info = CacheKit.get("permission", id);
        if (info == null) {
            info = new SimpleAuthorizationInfo();
            // 查找角色
            List<Role> userRoles = Role.dao.findListByUserId(id);
            if (!CollectionUtils.isEmpty(userRoles)) {
                for (Role userRole : userRoles) {
                    info.addRole(userRole.getSign());
                    // 角色存在，查找角色的权限
                    List<Permission> rolePermissions = Permission.dao.findListByRoleId(userRole.getInt("id"));
                    if (!CollectionUtils.isEmpty(rolePermissions)) {
                        for (Permission rolePermission : rolePermissions) {
                            info.addStringPermission(rolePermission.getSign());
                        }
                    }
                }
            }
            // 通过用户id查询权限
            List<Permission> userPermissions = Permission.dao.findListByUserId(id);
            if (!CollectionUtils.isEmpty(userPermissions)) {
                for (Permission permission : userPermissions) {
                    info.addStringPermission(permission.getSign());
                }
            }
            CacheKit.put("permission", id, info);
        }
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = String.valueOf(authenticationToken.getPrincipal());
        User user = User.dao.findByUserName(username);
        if (StrKit.notNull(user)) {
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        }
        throw new UnknownAccountException();
    }
}
